<?php

// ------------------------------------------------------------------------
// |@Author       : Jarmin <topextend@qq.com>
// |@----------------------------------------------------------------------
// |@Date         : 2025-05-09 19:02:22
// |@----------------------------------------------------------------------
// |@LastEditTime : 2025-05-14 02:08:21
// |@----------------------------------------------------------------------
// |@LastEditors  : Jarmin <topextend@qq.com>
// |@----------------------------------------------------------------------
// |@Description  :
// |@----------------------------------------------------------------------
// |@FilePath     : SystemRepository.php
// |@----------------------------------------------------------------------
// |@Copyright (c) 2025 http://www.ladmin.cn All Rights Reserved.
// ------------------------------------------------------------------------
declare (strict_types=1);

namespace think\admin\repository;

use think\admin\Repository;
use think\admin\model\SystemConfig;
use think\admin\model\SystemConfigGroup;

/**
 * 系统配置仓库
 * Class SystemRepository
 * @package think\admin\repository
 */
class SystemRepository extends Repository
{
    /**
     * 系统初始化
     * @return void
     */
    public function initialize(): void
    {
        // 注册系统配置主模型
        $this->model = new SystemConfigGroup();
        // 注册系统配置分组模型
        $this->registerModel('SystemConfig', new SystemConfig());
    }

    /**
     * 获取系统配置
     * @param int|null $site_id 站点ID
     * @param string|null $code 分组编码
     * @return array|null
     */
    public function getConfig(?string $code = null, ?int $site_id = 0): ?array
    {
        return $this->remember("system_config:" . ($code ?: 'All'), function () use ($site_id, $code) {
            $groups = $this->model->getWithConfigs($site_id, $code);
            return array_reduce($groups, function ($result, $group) {
                $result[$group['code']] = array_column($group['configs'], 'value', 'code');
                return $result;
            }, []);
        });
    }

    /**
     * 设置系统配置
     * @param string $key 配置键名
     * @param mixed $value 配置值
     * @param string $code 分组编码
     * @return int
     */
    public function setConfig(string $key, mixed $value, string $code): int
    {
        $result = $this->getModel('SystemConfig')->where(['code' => $key])
            ->with('group', function ($query) {
                $query->where(['code' => $code]);
            })->update(['value' => $value]);
        if ($result) {
            $this->deleteCache('system_config:' . $code);
            $this->deleteCache('system_config:All');
        }
        return $result;
    }
}
